package spindles.gwt.server;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;

import net.sf.dozer.util.mapping.DozerBeanMapperSingletonWrapper;
import net.sf.dozer.util.mapping.MapperIF;

import org.antlr.stringtemplate.StringTemplate;
import org.antlr.stringtemplate.StringTemplateGroup;

import spindles.api.util.Config;

import com.mathworks.toolbox.javabuilder.MWException;
import com.mathworks.toolbox.javabuilder.webfigures.WebFigure;
import com.mathworks.toolbox.javabuilder.webfigures.WebFigures;

public class ServletUtil {
	
	private ServletContext servletContext;
	
	private static ServletUtil instance;
	
	private MapperIF mapper = DozerBeanMapperSingletonWrapper.getInstance();
	
	public static final String DOC_BASE = "/spindles/";
	
	private ServletUtil(){
		
	}
	
	public static void init(ServletContext sc){		
		instance = new ServletUtil();
		instance.servletContext = sc;
	}	
	
	public static Object map(Object source, Class destination){
		return instance.mapper.map(source, destination);
	}
	
	@SuppressWarnings("unchecked")
	public static <T> List map(Collection<T> sourceObjects, Class destination){
		List result = new ArrayList();
		
		for(T obj : sourceObjects){			
			result.add(ServletUtil.map(obj, destination));
		}
		return result;		
	}
	
	public static StringTemplate getStringTemplate(String templateName) {
		String templatesPath = instance.servletContext.getRealPath("/WEB-INF/templates");

		StringTemplateGroup group = new StringTemplateGroup("templateGroup",
				templatesPath);
		return group.getInstanceOf(templateName);
	}
	
	public static String getWebFigureHTML(WebFigure wf, String webFigureName) throws MWException{
		WebFigures webFigures = new WebFigures("WebFigures", instance.servletContext);
		
		return webFigures.getHtmlEmbedString(wf, webFigureName, 
				"session", Config.getPlotWidth(), Config.getPlotHeight(), Config.getPlotCSS());
	}
	
	public static File getSessionExpDir(HttpSessionEvent se){
		return getSessionExpDir(se.getSession());
	}
	
	public static File getSessionExpDir(HttpSession s){
		String rootPath = s.getServletContext().getRealPath("/");		
		File f = new File(rootPath + s.getId());
		
		return f;
	}
	
	public static String getSessionExpPath(HttpSession s){		
		return getSessionExpDir(s).getAbsolutePath();
	}
	
	public static void setImportStatus(boolean importing){
		if(importing){
			instance.servletContext.setAttribute("imp.busy", true);
		} else{
			instance.servletContext.setAttribute("imp.busy", false);
		}
	}
	
	public static boolean isImporting() {

		Boolean isImporting = (Boolean) instance.servletContext.getAttribute(
				"imp.busy");

		return isImporting != null && isImporting;
	} 
	
	

}
